<template>
  <div class="star-rating">
    <svg
      v-for="(star, index) in maxStars"
      :key="index"
      class="star"
      viewBox="0 0 24 24"
      width="30"
      height="30"
      xmlns="http://www.w3.org/2000/svg"
      @click="setRating(index + 1)"
    >
      <defs>
        <linearGradient :id="'gradient-' + index" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stop-color="#ffc154" />
          <stop :offset="getStarFillPercentage(index)" stop-color="#ffc154" />
          <stop :offset="getStarFillPercentage(index)" stop-color="#dce3e6" />
          <stop offset="100%" stop-color="#dce3e6" />
        </linearGradient>
      </defs>
      <path
        :fill="'url(#gradient-' + index + ')'"
        d="M12 .587l3.668 7.431L24 9.588l-6 5.84 1.416 8.257L12 18.897l-7.416 4.788L6 15.428 0 9.587l8.332-1.57z"
      />
    </svg>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
  modelValue: {
    type: Number,
    default: 0,
  },
  maxStars: {
    type: Number,
    default: 5,
  },
});

const emit = defineEmits(['update:modelValue']);

const rating = ref(props.modelValue);

const setRating = (star) => {
  // return
  rating.value = star;
  emit('update:modelValue', rating.value);
};

const getStarFillPercentage = (index) => {
  const starRating = rating.value - index;
  if (starRating >= 1) {
    return '100%'; // Full width of the star
  } else if (starRating > 0) {
    return `${starRating * 100}%`; // Partial width of the star
  } else {
    return '0%'; // No width for the star
  }
};
</script>

<style scoped>
.star-rating {
  display: flex;
  margin-left: 0;
}

.star {
  cursor: pointer;
  fill: none;
  /* stroke: #dce3e6; */
  stroke-width: 2;
  transition: fill 0.2s;
  margin: 2px;
}
</style>
